import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoSever {
    //模拟实现一个Tcp协议的回显服务器；
    private ServerSocket serverSocket=null;
    public TcpEchoSever(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    //进行服务器的启动操作；
    public void start() throws IOException {
        ExecutorService executorService=Executors.newCachedThreadPool();
        System.out.println("启动服务器");
        while(true){
            //进行与客户端建立连接；
            Socket clintPacket=serverSocket.accept();
            //进行通过线程池来处理连接；
            executorService.submit(()->{
                    processConnection(clintPacket);
                });
        }
    }
    public void processConnection(Socket clintPacket){
        //进行处理连接；
        System.out.printf("[%s:%d] 客户端上线!\n",clintPacket.getInetAddress(),clintPacket.getPort());
        try(InputStream inputStream=clintPacket.getInputStream();
            OutputStream outputStream=clintPacket.getOutputStream();
        ) {
            Scanner scanner=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);
            while(true){
            if(!scanner.hasNext()){
                System.out.printf("[%s:%d] 客户端下线!\n",clintPacket.getInetAddress(),clintPacket.getPort());
                break;
            }
            String request=scanner.next();
            String response=process(request);
            printWriter.println(response);
            printWriter.flush();
                System.out.printf("[%s:%d] req: %s, resp: %s\n",
                        clintPacket.getInetAddress()
                        ,clintPacket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public String  process(String request){
        return request;
    }
    public static void main(String[] args) throws IOException {
        TcpEchoSever tcpEchoSever=new TcpEchoSever(9090);
        tcpEchoSever.start();
    }
}
